<template>
  <div>
    <div style="margin: 10px 0px">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input
              style="width: 200px"
              placeholder="宿舍楼栋"
              suffix-icon="el-icon-search"
              v-model="dormitoryBuilding"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-input
              style="width: 200px"
              placeholder="门牌号"
              suffix-icon="el-icon-search"
              v-model="dormitoryNumber"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-input
              style="width: 200px"
              placeholder="姓名"
              suffix-icon="el-icon-search"
              v-model="userName"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-input
              style="width: 200px"
              placeholder="手机号"
              suffix-icon="el-icon-search"
              v-model="phone"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="status" placeholder="状态">
            <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-button class="ml-5" type="primary" @click="load()">搜索</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
      </el-row>
    </div>

    <div style="margin: 10px 0">
      <el-button
        type="primary"
        @click="handleAdd"
        >新增 <i class="el-icon-circle-plus-outline"></i
      ></el-button>
      <el-popconfirm
        class="ml-5"
        confirm-button-text="确定"
        cancel-button-text="我再想想"
        icon="el-icon-info"
        icon-color="red"
        title="您确定批量删除这些数据吗？"
        @confirm="delBatch"
      >
        <el-button type="danger" slot="reference"
          >批量删除 <i class="el-icon-remove-outline"></i
        ></el-button>
      </el-popconfirm>
    </div>

    <el-table
        :data="tableData"
        border
        stripe
        :header-cell-class-name="'headerBg'"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="dormitoryBuilding" label="宿舍楼栋"></el-table-column>
      <el-table-column prop="dormitoryNumber" label="门牌号"></el-table-column>
      <el-table-column prop="userName" label="姓名"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="status" label="状态"></el-table-column>
      <el-table-column prop="urlList" label="故障图片" width="200">
        <template v-slot:default="scope">
          <div v-for="url in scope.row.urlList" :key="url">
            <div class="demo-image__preview">
              <el-image
                  style="width: 100px; height: 100px"
                  :src="url"
                  :preview-src-list="scope.row.urlList">
              </el-image>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="400" align="center">
        <template slot-scope="scope">
          <el-button
              type="primary"
              @click="handleStatus(scope.row)"
          >处理 <i class="el-icon-check"></i
          ></el-button>
          <el-button
              type="success"
              @click="handleEdit(scope.row)"
          >编辑 <i class="el-icon-edit"></i
          ></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text="确定"
              cancel-button-text="我再想想"
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="remove(scope.row)"
          >
            <el-button type="danger" slot="reference"
            >删除 <i class="el-icon-remove-outline"></i
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog title="报修信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form label-width="90px" size="small">
        <el-form-item label="宿舍信息">
          <el-cascader
              v-model="dormitoryIdList"
              :options="dormitoryList"
              @change="handleDormitoryChange"
              clearable></el-cascader>
        </el-form-item>
        <el-form-item label="学生信息">
          <el-cascader
              v-model="userIdList"
              :options="userList"
              clearable></el-cascader>
        </el-form-item>
        <el-form-item label="故障描述">
          <el-input
              v-model="form.description"
              autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="故障图片">
          <el-upload
              action="#"
              :http-request="handlerChange"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :before-upload="beforeAvatarUpload"
              :file-list="chooseFileList"
              :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "AidKit",
  data() {
    return {
      statusList: [{
        value: '已处理',
        label: '已处理'
      }, {
        value: '未处理',
        label: '未处理'
      }],
      urlList: [],
      chooseFileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      form: {},
      tableData: [],
      queryPageReuqest: {},
      dormitoryBuilding: "",
      dormitoryNumber: "",
      userName: "",
      phone: "",
      status: "",
      userIdList: [],
      userList: [],
      dormitoryList: [],
      dormitoryIdList: [],
      multipleSelection: [],
      filesList: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      user: localStorage.getItem("user")
          ? JSON.parse(localStorage.getItem("user"))
          : {},
      primaryKey: "",
    };
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      if (this.user.role != "ROLE_ADMIN") {
        this.queryPageReuqest.userId = this.user.id.toString();
      }
      this.queryPageReuqest.pageNo = this.pageNum;
      this.queryPageReuqest.pageSize = this.pageSize;
      this.queryPageReuqest.dormitoryBuilding = this.dormitoryBuilding;
      this.queryPageReuqest.dormitoryNumber = this.dormitoryNumber;
      this.queryPageReuqest.userName = this.userName;
      this.queryPageReuqest.phone = this.phone;
      this.queryPageReuqest.status = this.status;
      console.log(this.queryPageReuqest);
      this.request
          .post("/repair/queryPage", this.queryPageReuqest)
          .then((res) => {
            this.tableData = res.records;
            this.total = res.total;
          });
    },
    reset() {
      this.dormitoryBuilding = "";
      this.dormitoryNumber = "";
      this.userName = "";
      this.phone = "";
      this.status = "";
      this.load();
    },
    save() {
      this.form.userId = this.userIdList[0];
      this.form.dormitoryId = this.dormitoryIdList[0];
      let fileIdList = [];
      this.chooseFileList.forEach((item, index) => {
        fileIdList.push(item.fileId)
      })
      this.form.fileIdList = fileIdList;
      if (this.form.id == null) {
        this.request.post("/repair/save", this.form).then((res) => {
          if (res.code === "200") {
            this.$message.success("保存成功");
            this.dialogFormVisible = false;
            this.load();
          } else {
            this.$message.error("保存失败");
          }
        });
      } else {
        this.request.post("/repair/update", this.form).then((res) => {
          if (res.code === "200") {
            this.$message.success("更新成功");
            this.dialogFormVisible = false;
            this.load();
          } else {
            this.$message.error("更新失败");
          }
        });
      }
    },
    handleAdd() {
      this.dialogFormVisible = true;
      this.form = {};
      this.dormitoryList = [];
      this.userList = [];
      this.dormitoryIdList = [];
      this.chooseFileList = [];
      this.request
          .post("/dormitory/getAll").then((res) => {
        res.forEach((item, index) => {
          let dormitoryInfo = {};
          dormitoryInfo.value = (item.dormitoryId);
          dormitoryInfo.label = (item.dormitoryBuilding + item.dormitoryNumber);
          this.dormitoryList.push(dormitoryInfo);
        })
      });
    },
    handleEdit(row) {
      this.dormitoryList = [];
      this.dormitoryIdList = [];
      this.userList = [];
      this.userIdList = [];
      this.chooseFileList = [];
      if (row.filesList != null) {
        row.filesList.forEach((item, index) => {
          this.chooseFileList.push(item);
        })
      }
      this.request
          .post("/dormitory/getAll").then((res) => {
        res.forEach((item, index) => {
          let dormitoryInfo = {};
          dormitoryInfo.value = (item.dormitoryId);
          dormitoryInfo.label = (item.dormitoryBuilding + item.dormitoryNumber);
          this.dormitoryList.push(dormitoryInfo);
        })
      });
      this.dormitoryIdList.push(row.dormitoryId);
      let req = row.dormitoryId;
      this.request
          .post("/dormitoryUser/getDormitoryUserList", {
            dormitoryId: req
          }).then((res) => {
        res.forEach((item, index) => {
          let userInfo = {};
          let dormitoryInfo = {};
          userInfo.value = (item.userId);
          userInfo.label = (item.userName);
          this.userList.push(userInfo);
        })
      });
      this.userIdList.push(row.userId);
      this.form = JSON.parse(JSON.stringify(row));
      this.primaryKey = this.form.id;
      this.dialogFormVisible = true;
    },
    handleStatus(row) {
      row.status = "已处理"
      this.request.post("/repair/updateStatus", row).then((res) => {
        if (res.code === "200") {
          this.$message.success("更新成功");
          this.dialogFormVisible = false;
          this.load();
        } else {
          this.$message.error("更新失败");
        }
      });
    },
    remove(row) {
      this.request.post("repair/delete", {
        id: row.id,
        repairId: row.repairId
      }).then((res) => {
        if (res.code === "200") {
          this.$message.success("删除成功");
          this.load();
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    delBatch() {
      let idList = this.multipleSelection.map((v) => v.id);
      let repairList = this.multipleSelection.map((v) => v.repairId);
      this.request.post("/repair/delete/batch", {
        ids: idList,
        repairIdList: repairList
      }).then((res) => {
        if (res.code === "200") {
          this.$message.success("批量删除成功");
          this.load();
        } else {
          this.$message.error("批量删除失败");
        }
      });
    },
    handleDormitoryChange(value) {
      this.request
          .post("/dormitoryUser/getDormitoryUserList", {
            dormitoryId: value[0]
          }).then((res) => {
        this.userIdList = [];
        this.userList = [];
        res.forEach((item, index) => {
          if (item.status == 'USING') {
            let userInfo = {};
            userInfo.value = (item.userId);
            userInfo.label = (item.userName);
            this.userIdList.push(item.userId);
            this.userList.push(userInfo);
          }
        })
      });
    },
    //移除图片
    handleRemove(file, fileInfoList) {
      this.chooseFileList.forEach((item, index) => {
        if (item.name == file.name) {
          this.chooseFileList.splice(index, 1);
        }
      })
    },
    //放大图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //上传图片
    async handlerChange(param) {
      let formData = new FormData();
      await formData.append("file", param.file);
      this.request.post("/file/saveFile", formData).then((res) => {
        this.chooseFileList.push(res);
      });
    },
    //上传图片前进行校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load();
    },
  }
};
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
